<template>
  <div>
    <van-nav-bar :title="t('home.refundReceive')" left-arrow @click-left="onClickLeft" placeholder fixed />

    <van-cell-group style="background: none">
      <scanning @keydownEnter="handleScan" ref="refundRef" :placeholder="t('refundReceive.pleaseScanningRefund')" :isFocus="true"
        :isReset="true"></scanning>

      <van-form @submit="onSubmit">
        <van-field v-model="form.returnNo" disabled :label="t('refundReceive.refundNumber')" class="mt-2" />
        <van-field v-model="form.customId" :label="t('refundReceive.customId')" />
        <van-field v-model="form.skuCategoryNum" disabled :label="t('refundReceive.skuCategoryNum')" />
        <van-field v-model="form.skuNum" disabled :label="t('refundReceive.skuNum')" />
        <van-field v-model="form.operateTypeDesc" disabled :label="t('refundReceive.operateTypeDesc')" />
        <!-- <div style="margin: 2vw">
          <van-button block type="primary" native-type="submit" :loading="submitLoading">{{ t('submit') }}</van-button>
        </div> -->
        <div v-if="isShowAll" style="max-height: calc(100vh - 340px); overflow-y: auto;">
          <div class="split" v-if="isShowSplit">
            <p>{{ t('refundReceive.split') }}</p>
            <scanning @keydownEnter="handleScanSku" :placeholder="t('refundReceive.pleaseScanningSku')" :isFocus="true"
              :isReset="true"></scanning>
            <van-field>
              <template #input>
                <van-col span="3" style="text-align: center">
                  {{ t('refundReceive.No') }}
                </van-col>
                <van-col span="6" style="text-align: center">
                  {{ t('SKU') }}
                </van-col>
                <van-col span="5" style="text-align: center">
                  {{ t('refundReceive.goodsName') }}
                </van-col>
                <van-col span="5" style="text-align: center">
                  {{ t('refundReceive.skuNum_') }}
                </van-col>
                <van-col span="5" style="text-align: center">
                  {{ t('refundReceive.receiveNum') }}
                </van-col>
              </template>
            </van-field>
            <div style="">
              <van-field v-for="(item, index) in orderFormList.list" :key="index * Math.random()">
                <template #input>
                  <van-col span="3" style="text-align: center">
                    {{ index + 1 }}
                  </van-col>
                  <van-col span="6" style="text-align: center">
                    {{ item.skuCode }}
                  </van-col>
                  <van-col span="5" style="text-align: center">
                    {{ item.goodsName }}
                  </van-col>
                  <van-col span="5" style="text-align: center">
                    {{ item.skuNum }}
                  </van-col>
                  <van-col span="5" style="text-align: center">
                    <van-field type="number" v-model.number="item.receiveNum" />
                  </van-col>
                </template>
              </van-field>
            </div>
          </div>
          <div class="photograph" v-if="isShowPhotograph">
            <p>{{ t('refundReceive.photograph') }}</p>
            <van-cell-group>
              <van-field :label="t('refundReceive.outerPackage')" required>
                <template #input>
                  <van-uploader v-model="headlessFormState.outerPackage" :max-count="1" preview-size="120px"
                    :upload-text="t('refundReceive.uploadPhoto')" :after-read="afterReadOuterPackage" />
                </template>
              </van-field>
              <van-field :label="t('refundReceive.productPackage')" required>
                <template #input>
                  <van-uploader v-model="headlessFormState.productPackage" :max-count="1" preview-size="120px"
                    :upload-text="t('refundReceive.uploadPhoto')" :after-read="afterReadProductPackage" />
                </template>
              </van-field>
              <van-field :label="t('refundReceive.productPhoto')" required>
                <template #input>
                  <van-uploader v-model="headlessFormState.productPhoto" :max-count="1" preview-size="120px"
                    :upload-text="t('refundReceive.uploadPhoto')" :after-read="afterReadProductPhoto" />
                </template>
              </van-field>
            </van-cell-group>
          </div>
        </div>
        <div
          style="margin: 20px 0px 0px; display: flex; justify-content: space-between; position: fixed; left: 0; right: 0; bottom: 0px;">
          <van-button v-if="isShowAbandonedGoods" block @click="abandonedGoodsRegistrate">{{ t('refundReceive.abandonedGoods') }}</van-button>
          <van-button block type="primary" @click="onSubmit" style="margin-left: 5px;">{{ t('submit') }}</van-button>
        </div>
      </van-form>
      <van-popup :show="show" round position="bottom" :style="{ height: '60%' }">
        <div class="p-2 mx-auto">
          <van-field>
            <template #input>
              <span class="w-full p-3 text-xl text-center text-gray">{{
                t("refundReceive.abandonedGoods")
              }}</span>
            </template>
          </van-field>
          <van-cell-group>
            <van-field v-model="headlessFormState.desc" required :label="t('refundReceive.locationCode')"
              :placeholder="t('refundReceive.pleaseEnterShelfNumber')" />
            <van-field :label="t('refundReceive.png')" required>
              <template #input>
                <van-uploader v-model="headlessFormState.externalPng" :max-count="1" preview-size="120px"
                  :upload-text="t('refundReceive.externalPng')" :after-read="afterReadExternal" />
              </template>
            </van-field>
            <van-field label=" ">
              <template #input>
                <van-uploader v-model="headlessFormState.expressPng" :max-count="1" preview-size="120px"
                  :upload-text="t('refundReceive.expressPng')" :after-read="afterReadExpress" />
              </template>
            </van-field>
            <van-field label=" ">
              <template #input>
                <van-uploader v-model="headlessFormState.goodsPng1" :max-count="1" preview-size="120px"
                  :upload-text="t('refundReceive.goodsPng')" :after-read="afterReadGoods1" />
              </template>
            </van-field>
            <van-field label=" ">
              <template #input>
                <van-uploader v-model="headlessFormState.goodsPng2" :max-count="1" preview-size="120px"
                  :upload-text="t('refundReceive.goodsPng')" :after-read="afterReadGoods2" />
              </template>
            </van-field>
            <van-field label=" ">
              <template #input>
                <van-uploader v-model="headlessFormState.goodsPng3" :max-count="1" preview-size="120px"
                  :upload-text="t('refundReceive.goodsPng')" :after-read="afterReadGoods3" />
              </template>
            </van-field>
            <van-field v-model="headlessFormState.remark" :label="t('refundReceive.remark')"
              :placeholder="t('refundReceive.pleaseEnterRemark')" />
          </van-cell-group>
          <van-field style="padding: 0;">
            <template #input>
              <van-button class="w-full p-8" type="primary" @click="abandonedGoodsSubmit">{{
                t("submit") }}</van-button>
              <van-button class="w-full p-8 mt-2" @click="show = false">{{
                t("cancel") }}</van-button>
            </template>
          </van-field>
        </div>
      </van-popup>
    </van-cell-group>
  </div>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import Scanning from "@/views/components/Scanning/index.vue";
import { postRequest, scanFail, scanSuccess } from "@/api";
import { AppToast } from "@/utils/appToast";
import { showFailToast, showSuccessToast } from "vant";
import { localStorage } from "@/utils/local-storage";
import {  STORAGE_USER_DATA_KEY } from '@/stores/mutation-type'

let isShowAbandonedGoods = ref(false);
let isShowAll = ref(true);
let isShowSplit = ref(false);
let isShowPhotograph = ref(false);
let show = ref(false);
const headlessFormState = reactive({
  show: false,
  storageBlock: "",
  time: "",
  desc: "",
  fileList: [],
  remark: '',
  externalPng: [],
  expressPng: [],
  goodsPng1: [],
  goodsPng2: [],
  goodsPng3: [],
  outerPackage: [],
  productPackage: [],
  productPhoto: [],
});
const { t } = useI18n();
const refundRef = ref(null)
const onClickLeft = () => history.back();
const submitLoading = ref(false);
const form = ref();
const resetForm = () => {
  form.value = {
    returnNo: undefined,
    customId: undefined,
    deliveredBoxNum: undefined,
    skuNum: undefined,
    arrivalBoxNum: undefined,
    operateTypeDesc: undefined,
  }
};

let formData = new FormData();
let formDataRefund = new FormData();

let orderFormList = reactive({ list: []});
let returnNoTemp = '';

const abandonedGoodsSubmit = () => {
  formData.set('returnNo', form.value.returnNo || returnNoTemp);
  formData.set('locationCode', headlessFormState.desc);
  formData.set('remark', headlessFormState.remark);
  formData.set('modifiedUser', localStorage.get(STORAGE_USER_DATA_KEY).userId);
  
  postRequest("/noCustomer/noCustomer", formData).then((response) => {
    if (response.returnCode === 10000) {
      AppToast('上传成功', "success");
      show.value = false;
      resetForm()
    } else {
      AppToast(response.message, "fail");
    }
  }).catch(() => {
    AppToast('上传失败', "fail");
  });
};

const afterReadExternal = (file) => {
  formData.set("outerPackage", file.file);
};
const afterReadExpress = (file) => {
  formData.set("label", file.file);
};
const afterReadGoods1 = (file) => {
  formData.set("productPhoto1", file.file);
};
const afterReadGoods2 = (file) => {
  formData.set("productPhoto2", file.file);
};
const afterReadGoods3 = (file) => {
  formData.set("productPhoto3", file.file);
};
const afterReadOuterPackage = (file) => {
  formDataRefund.set('outerPackage', file.file);
};
const afterReadProductPackage = (file) => {
  formDataRefund.set('productPackage', file.file);
};
const afterReadProductPhoto = (file) => {
  formDataRefund.set('productPhoto', file.file);
};

resetForm();
const handleScan = returnNo => {
  resetForm();
  returnNoTemp = returnNo
  postRequest(
    '/inbound/getByReturnNo',
    { returnNo }
  ).then(res => {
    scanSuccess()
    if (res?.data && Object.keys(res.data).includes('customId')) {
      isShowAbandonedGoods.value = false;
    } else {
      isShowAbandonedGoods.value = true;
      headlessFormState.desc = ''
      headlessFormState.externalPng = []
      headlessFormState.expressPng = []
      headlessFormState.goodsPng1 = []
      headlessFormState.goodsPng2 = []
      headlessFormState.goodsPng3 = []
      headlessFormState.remark = ''
    }
  
    if (!res || res.returnCode !== 10000) return
    form.value = {
      ...res.data
    }
    form.value.returnNo = returnNo
    form.value.operateTypeDesc = form.value.operateTypeDesc || '不拆'
   
  
    if (res.data?.operateTypeDesc?.includes('拆分')) {
      isShowSplit.value = true;
    } else {
      isShowSplit.value = false;
    }
    if (res.data?.operateTypeDesc?.includes('拍照')) {
      isShowPhotograph.value = true;
    } else {
      isShowPhotograph.value = false;
    }
  
    orderFormList.list = res.data?.orderSkuBOList?.map(item => {
      item.receiveNum = 0;
      return item;
    }) || [];
  }).catch(() => {
    scanFail()
  })
};

const handleScanSku = sku => {  
  let info = orderFormList.list.find(item => item.skuCode === sku);
  if (info) {
    scanSuccess()
    info.receiveNum++;
  } else {
    scanFail()
  }
}

const abandonedGoodsRegistrate = () => {
  show.value = true;
  formData = new FormData();  
}

const onSubmit = async () => {
  if (form.value?.operateTypeDesc?.includes('拆分')) {
    let flag = orderFormList.list.every(item => {
      return item.skuNum == item.receiveNum;
    })
    
    if (!flag) {
      showFailToast('接收数量和预报数量不匹配，请核对后再提交');
      return;
    }
  }
  
  const {
    customId,
  } = form.value;
  
  if (!customId) {
    showFailToast(t('refundReceive.customIdEmpty'))
    return
  }
  submitLoading.value = true;
  formDataRefund.set('id', form.value.id);
  formDataRefund.set('customId', form.value.customId);
  const res = await postRequest(
    '/inbound/arrive', formDataRefund).finally(() => {
    submitLoading.value = false
  })
  if (!res || res.returnCode !== 10000) return
  showSuccessToast(t('success'))
  resetForm();
  refundRef.value.setFocus();
  isShowSplit.value = false;
  isShowPhotograph.value = false;
}
</script>

<style scoped lang="less">
:deep(.van-cell) {
  font-size: 1rem;
}

:deep(.van-nav-bar__title) {
  font-size: 1rem;
  font-weight: 500;
  color: white;
}

:deep(.van-nav-bar__content) {
  background: #1b82d2;
}

:deep(.van-nav-bar .van-icon) {
  color: white;
}

:deep(.van-button) {
  font-size: 1rem;
}

:deep(.van-field--disabled .van-field__label) {
  color: black;
}

</style>